/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.members.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.RechargeType;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.members.MemberCardTypeRepository;
import com.qinyeit.serviceapp.service.branchs.BranchDataReleasedServiceImpl;
import com.qinyeit.serviceapp.service.members.MemberCardTypeBranchService;
import com.qinyeit.serviceapp.service.members.MemberCardTypeService;
import com.qinyeit.serviceapp.service.members.RechargeRuleService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.pays.DiscountPlanService;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.repository.jdbc.PageNamedParameterJdbcTemplate;
import com.qinyetech.springstage.core.service.BaseService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/** 
 * ClassName: MemberCardTypeServiceImpl <br/> 
 * Function: 会员卡类型 业务实现 <br/> 
 * date: 2018-12-03 14:58:01 <br/> 
 * 
 * @author DESKTOP-DHS6NG3
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class MemberCardTypeServiceImpl extends BaseService<MemberCardType, Long> implements MemberCardTypeService {


	@Autowired
	private MemberCardTypeRepository memberCardTypeRepository;
	@Autowired
	private DiscountPlanService discountPlanService;
	@Autowired
	private RechargeRuleService rechargeRuleService;
	@Autowired
	private MemberCardTypeBranchService memberCardTypeBranchService;
	@Autowired
	private BranchService branchService;
	@Autowired
	private BranchDataReleasedServiceImpl branchDataReleasedService;
	@Autowired
	private PageNamedParameterJdbcTemplate jdbcTemplate;



	@Override
	public void saveData(JSONObject data, Long merchantGroupId, String operator) {
		JSONObject typeData = data.getJSONObject("types");
		JSONArray branchs = data.getJSONArray("branchs");
		JSONArray rules = data.getJSONArray("rules");
		if(typeData==null){
			throw new BusinessRunTimeException("请填写会员卡类型信息",10000);
		}
		if (CollectionUtils.isEmpty(branchs)){
			throw new BusinessRunTimeException("请选择适用门店",100001);
		}
		if(typeData.getBoolean("rechargeRule") && CollectionUtils.isEmpty(rules)){
			throw new BusinessRunTimeException("请填写充值规则",10002);
		}

		Long id = typeData.getLong("id");
		if (this.exists(SearchUtils.buildExists(id,"name",typeData.getString("name"),merchantGroupId))){
			throw new BusinessRunTimeException("会员卡类型名称已存在",10003);
		}
		MemberCardType cardType = null;
		List<Long> branchIds = null;
		if (id==null){
			cardType = new MemberCardType();
			cardType.setUuid(LocalUtils.getUUID());
		}else {
			//查找适用门店
			branchIds = this.getBranchList(id,merchantGroupId);
			cardType = this.findById(id);
			//删除门店
			memberCardTypeRepository.deleteBranchs(id);
			//删除积分规则
			memberCardTypeRepository.deleteRules(id);
		}
		cardType.setUpdateTimestamp(DateUtils.current());
		cardType.setMerchantGroupId(merchantGroupId);
		cardType.setName(typeData.getString("name"));
		cardType.setDiscountId(typeData.getLong("discountId"));
		cardType.setHasVipPrice(typeData.getBoolean("hasVipPrice"));
		cardType.setHasConsumeRecharge(typeData.getBoolean("hasConsumeRecharge"));
		if(typeData.getBoolean("hasConsumeRecharge")){
			cardType.setConsumePrice(typeData.getDouble("consumePrice"));
			cardType.setGiftPoint(typeData.getDouble("giftPoint"));
		}
		cardType.setRechargeRule(typeData.getBoolean("rechargeRule"));
		JSONObject item ;
		if(typeData.getBoolean("rechargeRule")){
			cardType.setRechargeType(RechargeType.valueOf(typeData.getString("rechargeType")));
		}
		cardType.setPointRule(data.getString("pointRule"));
		cardType.setHasUseRule(typeData.getBoolean("hasUseRule"));
		cardType.setUseRuleDetail(typeData.getString("useRuleDetail"));
		cardType = this.update(cardType);
		List<RechargeRule> ruleList = null;
		if(typeData.getBoolean("rechargeRule")){
			ruleList = Lists.newArrayList();
			//保存规则
			RechargeRule rule = null;
			for (int i = 0; i < rules.size(); i++) {
				item = rules.getJSONObject(i);
				rule = new RechargeRule();
				rule.setCategoryId(cardType.getId());
				rule.setType(cardType.getRechargeType());
				rule.setRangeStart(item.getDouble("rangeStart"));
				rule.setRangeEnd(item.getDouble("rangeEnd"));
				rule.setGiftMoney(item.getDouble("giftMoney"));
				rule.setGiftPoint(item.getDouble("giftPoint"));
				rule.setMerchantGroupId(merchantGroupId);
				rule = rechargeRuleService.save(rule);
				ruleList.add(rule);
			}
		}

		MemberCardTypeBranch typeBranch = null;
		Branch branch = null;
		List<Long> merchantIds = Lists.newArrayList();
		for (int i = 0; i < branchs.size(); i++) {
			typeBranch = new MemberCardTypeBranch();
			branch = branchService.findById(branchs.getLong(i));
			merchantIds.add(branch.getMerchantId());
			typeBranch.setBranchId(branchs.getLong(i));
			typeBranch.setDistrictId(branch.getDistrictId());
			typeBranch.setMemberCardTypeId(cardType.getId());
			typeBranch.setMerchantGroupId(merchantGroupId);
			memberCardTypeBranchService.save(typeBranch);
		}

		//会员卡类型同步到单店
		branchDataReleasedService.updateMemberCardTypes(merchantIds,merchantGroupId,cardType,ruleList);


		if (CollectionUtils.isNotEmpty(branchIds)){
			//编辑
			List<Long> newBranchs= branchs.toJavaList(Long.class);
			List<Long> oldBranchs = Lists.newArrayList(branchIds);
			//求新添加的
			List<Long> insertIds =newBranchs.stream().filter(t-> !oldBranchs.contains(t)).collect(Collectors.toList());


			log.info("insertIds:{}",JSON.toJSONString(insertIds));
			//减去的 先移除新添加的
			newBranchs.removeAll(Lists.newArrayList(insertIds));
			//过滤不包含的
			List<Long> subtractIds =oldBranchs.stream().filter(t-> !newBranchs.contains(t)).collect(Collectors.toList());
			log.info("subtractIds:{}",JSON.toJSONString(subtractIds));

			//将新添加的门店 对应的会员卡 / 会员 添加到门店中
			branchDataReleasedService.saveOtherMemberAndMemberCard(insertIds,cardType);
		}

	}

	@Override
	public void updateData(Long id, Long merchantGroupId) {
		MemberCardType memberCardType = this.findByIdAndClear(id);
		memberCardType.setDeleted(true);
		memberCardType.setUpdateTimestamp(DateUtils.current());
		memberCardType = this.update(memberCardType);
		log.info(JSON.toJSONString(memberCardType));
		log.info("type ss : {}",memberCardType.isDeleted());
		Searchable searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
		searchable.addSearchParam("memberCardTypeId_eq",id);
		List<MemberCardTypeBranch> branchList = memberCardTypeBranchService.findWithSort(searchable);
		List<RechargeRule> ruleList = null;
		if (memberCardType.getRechargeRule()){
			searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
			searchable.addSearchParam("categoryId_eq",memberCardType.getId());
			ruleList = rechargeRuleService.findWithSort(searchable);
		}

		if (CollectionUtils.isNotEmpty(branchList)){
			List<Long> branchIds = branchList.stream().map(MemberCardTypeBranch::getBranchId).collect(Collectors.toList());
			List<Long> merchantIds = new ArrayList<>(branchDataReleasedService.changeMerchants(branchIds)); //直接构造函数即可
			branchDataReleasedService.updateMemberCardTypes(merchantIds,merchantGroupId,memberCardType,ruleList);
		}
	}

	@Override
	public List<Long> getBranchList(Long id, Long merchantGroupId) {
		Searchable searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
		searchable.addSearchParam("memberCardTypeId_eq",id);
		List<MemberCardTypeBranch> branchList = memberCardTypeBranchService.findWithSort(searchable);
		if (CollectionUtils.isEmpty(branchList)){
			return null;
		}
		return branchList.stream().map(MemberCardTypeBranch::getBranchId).collect(Collectors.toList());
	}
}